﻿//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;

//using System.Runtime.InteropServices;

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

using Autodesk.AutoCAD.Windows;

namespace ARXLab_DotNet
{
    public class adskClass
    {
        [CommandMethod("HelloWorld")]
        public void HelloWord()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("Hello World");
        }

        [CommandMethod("addAnEnt")]
        public static void AddAnEnt() {
            // get the editor object so we can carry out some input
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("Editor get success");
            // first decide what type of entity we want to create
            PromptKeywordOptions getWhichEntityOptions = new PromptKeywordOptions("Which entity do you want to create? [Circle/Block]:","Circle blcok");
            // now input it
            PromptResult getWhichEntityResult = ed.GetKeywords(getWhichEntityOptions);
            if (getWhichEntityResult.Status == PromptStatus.OK)         // if ok
            {
                switch (getWhichEntityResult.StringResult)
                {
                    case "Circle":
                        // pick the center point of the circle
                        PromptPointOptions getPointOptions = new PromptPointOptions("Pick Center Point:");
                        PromptPointResult getPointResult = ed.GetPoint(getPointOptions);
                        if (getPointResult.Status == PromptStatus.OK)
                        {
                            // get the radius
                            PromptDistanceOptions getRadiusOptions = new PromptDistanceOptions("Pick Radius:");
                            // set the start point to the center (the point we just picked)
                            getRadiusOptions.BasePoint = getPointResult.Value;
                            // new tell the input mechanism to actually use the basepoint!
                            getRadiusOptions.UseBasePoint = true;
                            // now get the radius
                            PromptDoubleResult getRadiusResult = ed.GetDistance(getRadiusOptions);
                            if (getRadiusResult.Status == PromptStatus.OK)
                            {
                                // need to add the circle to the current space
                                // get the current working database
                                Database dwg = ed.Document.Database;

                                // now start a transaction
                                Transaction trans = dwg.TransactionManager.StartTransaction();
                                try
                                {
                                    // create a new circle
                                    Circle circle = new Circle(getPointResult.Value, Vector3d.ZAxis, getRadiusResult.Value);
                                    // open the current space (block table record) for write
                                    BlockTableRecord btr = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite);
                                    // now the circle to the current space, model space more than likely
                                    btr.AppendEntity(circle);
                                    // tell the transaction about the new circle so that it can autoclose it
                                    trans.AddNewlyCreatedDBObject(circle, true);
                                    // now commit the transaction
                                    trans.Commit();
                                }
                                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                                {
                                    ed.WriteMessage("Autodesk promblem due to " + ex.Message);
                                }
                                catch (System.Exception ex) {
                                    ed.WriteMessage("C# promblem due to " + ex.Message);
                                }
                                finally
                                {
                                    // all done, whether an error or not - dispose the transaction
                                    trans.Dispose();
                                }
                            }
                        }
                        break;
                    case "Block":
                        // enter the name of the block
                        PromptStringOptions blockNameOptions = new PromptStringOptions("Enter name of Block to create:");
                        // no spaces are allowed in a blcokname so disable it
                        blockNameOptions.AllowSpaces = false;
                        // get the name;
                        PromptResult blockNameResult = ed.GetString(blockNameOptions);
                        if (blockNameResult.Status == PromptStatus.OK)
                        {
                            // lets create the block defination
                            // get the curring drawing
                            Database dwg = ed.Document.Database;
                            // new start a transaction
                            Transaction trans = (Transaction)dwg.TransactionManager.StartTransaction();
                            try {
                                // create the new block definition
                                BlockTableRecord newBlockDef = new BlockTableRecord();
                                // name the block definition
                                newBlockDef.Name = blockNameResult.StringResult;
                                // now add the new block definition to the block table
                                // open the block table for read so we can check to see if the name already exists
                                BlockTable blocktable = (BlockTable)trans.GetObject(dwg.BlockTableId, OpenMode.ForRead);
                                // check to see if the block already exists
                                if (blocktable.Has(blockNameResult.StringResult) == false)
                                {
                                    // if it's not there, then we are ok to add it
                                    // but first we need to upgrade the open to write
                                    blocktable.UpgradeOpen();
                                    // Add the BlockTableRecord to the blockTable
                                    blocktable.Add(newBlockDef);
                                    // tell the transaction manager about the new object so that the transaction will autoclose it
                                    trans.AddNewlyCreatedDBObject(newBlockDef, true);

                                    // now add some objects to the block definition
                                    Circle circle1 = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, 10);
                                    newBlockDef.AppendEntity(circle1);
                                    Circle circle2 = new Circle(new Point3d(20, 10, 0), Vector3d.ZAxis, 10);
                                    newBlockDef.AppendEntity(circle2);

                                    // tell the transaction manager about the new objects
                                    // so that the transaction will autoclose it
                                    trans.AddNewlyCreatedDBObject(circle1, true);
                                    trans.AddNewlyCreatedDBObject(circle2, true);

                                    // now set where it should appear in the current space
                                    PromptPointOptions blockRefPointOptions = new PromptPointOptions("Pick insert point of BlockRef:");
                                    PromptPointResult blockRefPointResult = ed.GetPoint(blockRefPointOptions);
                                    // check to see if everything was ok - if not
                                    if (blockRefPointResult.Status != PromptStatus.OK)
                                    {
                                        trans.Dispose();
                                        return;
                                    }

                                    // now we have the block definition in place and the position we need to create the reference to it
                                    BlockReference blockRef = new BlockReference(blockRefPointResult.Value, newBlockDef.ObjectId);
                                    // otherwise add it to the current space, first open the current space for write
                                    BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite);
                                    // now add the block reference to it
                                    curSpace.AppendEntity(blockRef);
                                    // remember to tell the transaction about the new block refercence so that the transaction can autoclose it
                                    trans.AddNewlyCreatedDBObject(blockRef, true);
                                    // all ok, commit it
                                    trans.Commit();
                                }
                            }
                            catch (Autodesk.AutoCAD.Runtime.Exception ex)
                            {
                                ed.WriteMessage("Autodesk promblem due to " + ex.Message);
                            }
                            catch (System.Exception ex)
                            {
                                ed.WriteMessage("C# promblem due to " + ex.Message);
                            }
                            finally
                            {
                                // whatever happens we must dispose the transaction
                                trans.Dispose();
                            }
                        }
                        break;
                }
            }
        }
        
        // LispFuntion creates a list callable function.
        // Many return types are supported not just string or integer
        /*
        [LispFunction("MyLispFunction", "MyLispFunctionLocal")]
        public int MyLispFunction(ResultBuffer args)
        {
            return 1;
        }
        */
        // delcare a paletteset object, this will only be created once
        public PaletteSet myPaletteSet;
        // we need a palette which will housed by the paletteSet
        public ARXLab_DotNet.UserControl1 myPalette;

        [CommandMethod("palette")]
        public void palette()
        {
            // check to see if is valid
            if (myPaletteSet == null)
            {
                // create a new palette set, with a unique guid
                myPaletteSet = new PaletteSet("My palette", new System.Guid("BE9F910E-6168-47C1-BFBF-EFEA62C87AD4"));
                // now create a palette inside, this has our tree control
                myPalette = new ARXLab_DotNet.UserControl1();
                // now add the palette to the paletteset
                myPaletteSet.Add("Palette1", myPalette);
            }
            // display the paletteset
            myPaletteSet.Visible = true;
        }

        [CommandMethod("addDBEvents")]
        public void addDBEvents()
        {
            // the palette needs to be created for this
            if (myPalette == null)
            {
                // get the editor object
                Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
                // now write the command line
                ed.WriteMessage("\n" + "Please call the 'palette' command first");
                return;
            }
            // get the current working databse
            Database curDwg = Application.DocumentManager.MdiActiveDocument.Database;
            // add handlers for what we need
            curDwg.ObjectAppended += new ObjectEventHandler(callback_ObjectAppended);
            curDwg.ObjectErased += new ObjectErasedEventHandler(callback_ObjectErased);
            curDwg.ObjectReappended += new ObjectEventHandler(callback_ObjectReappended);
            curDwg.ObjectUnappended += new ObjectEventHandler(callback_ObjectUnappended);
        }

        private void callback_ObjectAppended(object sender, ObjectEventArgs e)
        {
            // add the class name of the object to the tree view
            System.Windows.Forms.TreeNode newNode = myPalette.treeView1.Nodes.Add(e.DBObject.GetType().ToString());
            // we need to record its id for recognition later
            newNode.Tag = e.DBObject.ObjectId.ToString();
        }

        private void callback_ObjectErased(object sender, ObjectErasedEventArgs e)
        {
            // if the object was erased
            if (e.Erased)
            {
                // find the object in the treeview control so we can remove it
                foreach (System.Windows.Forms.TreeNode node in myPalette.treeView1.Nodes)
                {
                    if (node.Tag.ToString() == e.DBObject.ObjectId.ToString())
                    {
                        node.Remove();
                        break;
                    }
                }
            }
            // if the object was unerased
            else
            {
                // add the class name of the object to the tree view
                System.Windows.Forms.TreeNode newNode = myPalette.treeView1.Nodes.Add(e.DBObject.GetType().ToString());
                newNode.Tag = e.DBObject.ObjectId.ToString();
            }
        }

        private void callback_ObjectReappended(object sender, ObjectEventArgs e)
        {
            System.Windows.Forms.TreeNode newNode = myPalette.treeView1.Nodes.Add(e.DBObject.GetType().ToString());
            newNode.Tag = e.DBObject.ObjectId.ToString();
        }

        private void callback_ObjectUnappended(object sender, ObjectEventArgs e) {
            foreach (System.Windows.Forms.TreeNode node in myPalette.treeView1.Nodes)
            {
                if (node.Tag.ToString() == e.DBObject.ObjectId.ToString())
                {
                    node.Remove();
                    break;
                }
            }
        }

        [CommandMethod("addData")]
        public void addData()
        {
            // get the editor object
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            // pick entity to add data to
            PromptEntityResult getEntityResult = ed.GetEntity("Pick an entity to add an Extension Dictionary to:");
            if (getEntityResult.Status == PromptStatus.OK)
            {
                // now start a transaction
                Transaction trans = ed.Document.Database.TransactionManager.StartTransaction();
                try
                {
                    // Declare an Entity variable named ent.
                    Entity ent = (Entity)trans.GetObject(getEntityResult.ObjectId, OpenMode.ForRead);
                    // test the IsNull property of the ExtensionDictionary of the ent.
                    if (ent.ExtensionDictionary.IsNull)
                    {
                        // Upgrade the open of the entity
                        ent.UpgradeOpen();
                        // Create the ExtensionDictionary
                        ent.CreateExtensionDictionary();
                    }
                    // variable of DBDictionary
                    DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead);
                    if (extensionDict.Contains("MyData"))
                    {
                        // Check to see if the entry we are going to add is already there
                        ObjectId entryID = extensionDict.GetAt("MyData");
                        // If this line gets hit then data is already added
                        ed.WriteMessage("\nThis entity already has data...");
                        Xrecord myXrecord = default(Xrecord);
                        // Extract the Xrecord. Declare an Xrecord variable.
                        myXrecord = (Xrecord)trans.GetObject(entryID, OpenMode.ForRead);
                        // Here print out the values in the Xrecord to the command line.
                        foreach (TypedValue value in myXrecord.Data)
                        {
                            ed.WriteMessage("\n" + value.TypeCode.ToString() + "." + value.Value.ToString());
                        }
                    }
                    else
                    {
                        // If the code gets to here then the data entry does not exist
                        // upgrade the ExtensionDictionary
                        extensionDict.UpgradeOpen();
                      
                        //System.Type t = typeof(DBDictionary);
                        
                        // Create a new XRecord
                        Xrecord myXrecord = new Xrecord();
                        // Create the resbuf list.
                        ResultBuffer data = new ResultBuffer(
                            new TypedValue((int)DxfCode.Int16, 1),
                            new TypedValue((int)DxfCode.Text, "MyStockData"),
                            new TypedValue((int)DxfCode.Real, 51.9),
                            new TypedValue((int)DxfCode.Real, 100.9),
                            new TypedValue((int)DxfCode.Real, 320.6));
                        // Add the ResultBuffer to the XRecord
                        myXrecord.Data = data;
                        // Create the entry in the ExtensionDictionary
                        extensionDict.SetAt("MyData", myXrecord);
                        // Tell the transaction about the newly created XRecord.
                        trans.AddNewlyCreatedDBObject(myXrecord, true);
                        // Here we will populate the treeview control with the new data
                        if (myPalette != null)
                        {
                            foreach (System.Windows.Forms.TreeNode node in myPalette.treeView1.Nodes)
                            {
                                // Test to see if the node Tag is the ObjectId of the ent.
                                if (node.Tag.ToString() == ent.ObjectId.ToString())
                                {
                                    // Now add the new data to the treenode.
                                    System.Windows.Forms.TreeNode childNode = node.Nodes.Add("Extension Dictionary");
                                    // Add the data.
                                    foreach (TypedValue value in myXrecord.Data)
                                    {
                                        // Add the value from the TypedValue
                                        childNode.Nodes.Add(value.ToString());
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    trans.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("Autodesk promblem due to " + ex.Message);
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage("C# promblem due to " + ex.Message);
                }
                finally
                {
                    // whatever happens we must dispose the transaction
                    trans.Dispose();
                }
            }
        }

        [CommandMethod("addDataToNOD")]
        public void addDataToNOD()
        {
            // get the editor object
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            // pick entity to add data to
            Transaction trans = ed.Document.Database.TransactionManager.StartTransaction();
            try
            {
                // Here we will add our data to the Named Ojbect Dictionary.(NOD)
                DBDictionary nod = (DBDictionary)trans.GetObject(ed.Document.Database.NamedObjectsDictionaryId, OpenMode.ForRead);
                if (nod.Contains("MyData"))
                {
                    // Check to see if our entry is in Named Objects Dictionary.
                    ObjectId entryID = nod.GetAt("MyData");
                    // If we are here, then the Named Object Dcitionary already has our data
                    ed.WriteMessage("\n" + "This entity already has data...");
                    // Get the Xrecord from the NOD
                    Xrecord myXrecord = null;
                    // Open the Xrecod for read
                    myXrecord = (Xrecord)trans.GetObject(entryID, OpenMode.ForRead);
                    // Print out the values of the Xrecord to the command line
                    foreach (TypedValue value in myXrecord.Data)
                    {
                        // Use the WriteMessage method of the editor.
                        ed.WriteMessage("\n" + value.TypeCode.ToString() + "." + value.Value.ToString());
                    }
                }
                else
                {
                    // Our data is not in the Named Objects Dictionary so need to add it
                    nod.UpgradeOpen();
                    // Declare a variable as a new Xrecord.
                    Xrecord myXrecord = new Xrecord();
                    // Create the resbuf list.
                    ResultBuffer data = new ResultBuffer(
                        new TypedValue((int)DxfCode.Int16, 1),
                        new TypedValue((int)DxfCode.Real, 51.9),
                        new TypedValue((int)DxfCode.Real, 100.9),
                        new TypedValue((int)DxfCode.Real, 320.6));
                    // Add the ResultBuffer to the Xrecord
                    myXrecord.Data = data;
                    // Create the entry in the ExtensionDictionary
                    nod.SetAt("MyData", myXrecord);
                    // Tell the transaction about the newly created Xrecord
                    trans.AddNewlyCreatedDBObject(myXrecord, true);
                }
                trans.Commit();
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("Autodesk promblem due to " + ex.Message);
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("C# promblem due to " + ex.Message);
            }
            finally
            {
                // whatever happens we must dispose the transaction
                trans.Dispose();
            }            
        }

        [CommandMethod("addPointmonitor")]
        public void startMonitor()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            // Connect to the PointMonitor event
            ed.PointMonitor += new PointMonitorEventHandler(MyPointMonitor);
        }

        public void MyPointMonitor(object sender, PointMonitorEventArgs e)
        {
            if (e.Context == null)
            {
                return;
            }
            // array of the Type FullSubentityPath type.
            FullSubentityPath[] fullEntPath = e.Context.GetPickedEntities();
            if (fullEntPath.Length > 0)
            {
                Transaction trans = Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction();
                try
                {
                    Entity ent = (Entity)trans.GetObject((ObjectId)fullEntPath[0].GetObjectIds()[0], OpenMode.ForRead);
                    // Add a tooltip by using the AppendToolTipText method
                    e.AppendToolTipText("The Entity is a " + ent.GetType().ToString());
                    // Make sure the palette has been created
                    if (myPalette == null)
                    {
                        return;
                    }
                    // The following steps will make the text of the entry for a DBEntity
                    System.Drawing.Font fontRegular = new System.Drawing.Font("Microsoft Sans Serif", 8, System.Drawing.FontStyle.Regular);
                    System.Drawing.Font fontBold = new System.Drawing.Font("Microsoft Sans Serif", 8, System.Drawing.FontStyle.Bold);
                    // Use the SuspendLayout() method of the treeview1 created in Lab4 to
                    // wait until after the steps below are processed.
                    this.myPalette.treeView1.SuspendLayout();
                    // Here we will search for an object in the treeview control so th font
                    // can be changed to bold.
                    foreach (System.Windows.Forms.TreeNode node in myPalette.treeView1.Nodes)
                    {
                        if (((string)node.Tag == ent.ObjectId.ToString()))
                        {
                            // if we get here then the node is the one we want
                            if (!fontBold.Equals(node.NodeFont))
                            {
                                // Make the NodeFont property of the node equal to the
                                // System.Drawing.Font variable created above
                                node.NodeFont = fontBold;
                                node.Text = node.Text;
                            }
                        }
                        else
                        {
                            // If we get here then the node is not the node we want.
                            if (!fontRegular.Equals(node.NodeFont))
                            {
                                node.NodeFont = fontRegular;
                            }
                        }
                    }
                    // Now it's time to recalc the layout of the treeview.
                    this.myPalette.treeView1.ResumeLayout();
                    this.myPalette.treeView1.Refresh();
                    this.myPalette.treeView1.Update();
                    // All is ok if we get here so Commit the transaction created in
                    trans.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                   
                }
                catch (System.Exception ex)
                {
                    
                }
                finally
                {
                    // whatever happens we must dispose the transaction
                    trans.Dispose();
                }      
            }
        }

        [CommandMethod("newInput")]
        public void NewInput()
        {
            // start our input point Monitor. 
            // get the editor object
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            // now add the delegate to the event list
            ed.PointMonitor += new PointMonitorEventHandler(MyInputMonitor);
            // Need to enable the AutoCAD input event mechanism to do a pick under the prevailing
            // pick aperturn on all digitizer events, regardless of whether a point is being acquired
            // or whether any OSNAP modes are currently active.
            ed.TurnForcedPickOn();
            // Here we are going to ask the user to pick a point.
            PromptPointOptions getPointOptions = new PromptPointOptions("Pick A Point:");
            PromptPointResult getPointResult = ed.GetPoint(getPointOptions);
            // if ok
            // ......... do something.
            //
            // Now remove our point monitor as we are finished With it.
            ed.PointMonitor -= new PointMonitorEventHandler(MyInputMonitor);
        }

        public void MyInputMonitor(object sender, PointMonitorEventArgs e)
        {
            if (e.Context == null)
            {
                return;
            }

            // first lets check what is under the Cursor
            FullSubentityPath[] fullEntPath = e.Context.GetPickedEntities();
            if (fullEntPath.Length > 0)
            {
                // start a transaction
                Transaction trans = Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction();
                try
                {
                    // open the Entity for read, it must be derived from Curve
                    Curve ent = (Curve)trans.GetObject(fullEntPath[0].GetObjectIds()[0], OpenMode.ForRead);
                    // ok, so if we are over something - then check to see if it has an extension dictionary
                    if (ent.ExtensionDictionary.IsValid)
                    {
                        // open it for read
                        DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead);
                        // find the entry
                        ObjectId entryID = extensionDict.GetAt("MyData");
                        // if we are here ,then all is ok. extract the xrecord
                        Xrecord myXrecord;
                        // read it from the extension dictionary
                        myXrecord = (Xrecord)trans.GetObject(entryID, OpenMode.ForRead);
                        // We will draw temporary graphics at certain positions along the entity
                        foreach (TypedValue myTypedVal in myXrecord.Data)
                        {
                            if (myTypedVal.TypeCode == (short)DxfCode.Real)
                            {
                                // To locate the temporary graphics along the Curve
                                // to show the distances we need to get the point along the curve.
                                Point3d pnt = ent.GetPointAtDist((double)myTypedVal.Value);
                                // We need to work out how many pixels are int a unit square
                                // so we can keep the temporary graphics a set size regardless of
                                // the zoom scale.
                                Point2d pixels = e.Context.DrawContext.Viewport.GetNumPixelsInUnitSquare(pnt);
                                // We need some constant distances.
                                double xDist = (10 / pixels.X);
                                double yDist = (10 / pixels.Y);
                                // Draw the temporay Graphids.
                                Circle circle = new Circle(pnt, Vector3d.ZAxis, xDist);
                                e.Context.DrawContext.Geometry.Draw(circle);
                                DBText text = new DBText();
                                // Always a good idea to set the Database defaults With things like
                                // text, dimensions etc.
                                text.SetDatabaseDefaults();
                                // Set the position of the text to the same point as the circle,
                                // but offset by the radius.
                                text.Position = (pnt + new Vector3d(xDist, yDist, 0));
                                // Use the data from the Xrecord for the text.
                                text.TextString = myTypedVal.Value.ToString();
                                text.Height = yDist;
                                // Use the Draw method to display the text.
                                e.Context.DrawContext.Geometry.Draw(text);
                            }
                        }
                    }
                    // all ok, commit it
                    trans.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {

                }
                catch (System.Exception ex)
                {

                }
                finally
                {
                    // whatever happens we must dispose the transaction
                    trans.Dispose();
                }      
            }
        }

        [CommandMethod("circleJig")]
        public void CircleJig()
        {
            Circle circle = new Circle(Point3d.Origin, Vector3d.ZAxis, 10);
            MyCircleJig jig = new MyCircleJig(circle);
            for (int i = 0; i <= 1; i++)
            {
                jig.CurrentInput = i;
                Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
                PromptResult promptResult = ed.Drag(jig);
                if (promptResult.Status == PromptStatus.Cancel | promptResult.Status == PromptStatus.Error)
                {
                    return;
                }
            }

            Database dwg = Application.DocumentManager.MdiActiveDocument.Database;
            Transaction trans = dwg.TransactionManager.StartTransaction();
            try
            {
                BlockTableRecord currentSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite);
                currentSpace.AppendEntity(circle);
                trans.AddNewlyCreatedDBObject(circle, true);
                trans.Commit();
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {

            }
            catch (System.Exception ex)
            {

            }
            finally
            {
                // whatever happens we must dispose the transaction
                trans.Dispose();
            }      
        }

  }

    class MyCircleJig : EntityJig
    {
        private Point3d centerPoint;
        private double radius;
        private int currentInputValue;
        public int CurrentInput
        {
            get { return currentInputValue; }
            set { currentInputValue = value; }
        }

        public MyCircleJig(Entity ent)
            : base(ent)
        {
        }

        protected override Autodesk.AutoCAD.EditorInput.SamplerStatus Sampler(
            Autodesk.AutoCAD.EditorInput.JigPrompts prompts)
        {
            switch (currentInputValue)
            {
                case 0:
                    Point3d oldPnt = centerPoint;
                    PromptPointResult jigPromptResult = prompts.AcquirePoint("Pick center point:");
                    if (jigPromptResult.Status == PromptStatus.OK)
                    {
                        centerPoint = jigPromptResult.Value;
                        if ((oldPnt.DistanceTo(centerPoint) < 0.001))
                        {
                            return SamplerStatus.NoChange;
                        }
                    }
                    return SamplerStatus.OK;
                case 1:
                    double oldResult = radius;
                    JigPromptDistanceOptions jigPromptDistanceOpts = new JigPromptDistanceOptions("Pick radius:");
                    jigPromptDistanceOpts.UseBasePoint = true;
                    jigPromptDistanceOpts.BasePoint = centerPoint;
                    PromptDoubleResult jigPromptDbResult = prompts.AcquireDistance(jigPromptDistanceOpts);
                    if (jigPromptDbResult.Status == PromptStatus.OK)
                    {
                        radius = jigPromptDbResult.Value;
                        if (System.Math.Abs(radius) < 0.1)
                        {
                            radius = 1;
                        }
                        if (System.Math.Abs(oldResult - radius) < 0.001)
                        {
                            return SamplerStatus.NoChange;
                        }
                    }
                    return SamplerStatus.OK;
            }
            return SamplerStatus.NoChange;
            //throw new NotImplementedException();
        }

        protected override bool Update()
        {
            switch (currentInputValue)
            {
                case 0:
                    ((Circle)this.Entity).Center = centerPoint;
                    break;
                case 1:
                    ((Circle)this.Entity).Radius = radius;
                    break;
            }
            return true;
            //throw new NotImplementedException();
        }

    }
}
